#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   EventHandle
@Time    :   2023/03/13 15:21:41
@author  :   Eval
@Version :   1.0
@Describe:   处理游戏行走中触发的事件
'''

from lib.scripts.ui.ShowDiaLog import ShowDiaLog
from time import sleep
from lib.scripts.GC import *
from lib.scripts.MapLogic import *
from lib.scripts.GameMusic import *
from lib.scripts.Package import Package

class EvHandle:
    def __init__(self,mg,music,bag) -> None:
        # 是否触发了事件,请务必禁止外部修改此值
        self.__Active = False
        self.mg:MapLogic = mg
        self.music:Music = music
        self.bag:Package = bag
        self.eventArr = None # 事件内容
        self.eventIndex = 0  # 当前事件索引
        self.eventStop = False  # 事件是否暂停执行
        # 对话事件的id
        self.msgID:str = None
        # 是否处于事件阻塞, (触发事件等需要手动操作时启用)
        # self.eventChoke = False
        self.eventTipClear = True

    def isActive(self):
        """提供外部调用,返回事件的激活状态"""
        return self.__Active
    
    def contactEvent(self,event:dict,x:int,y:int):
        """触发事件"""
        self.eventArr = event.get(f"{x},{y}")
        self.eventIndex = 0
        self.eventStop = False
        self.msgID = None
        self.eventTipClear = True
        while self.eventIndex < len(self.eventArr) and self.eventTipClear:
            e = self.eventArr[self.eventIndex]

            if not self.eventStop:
                # 如果事件没有被暂停,且没有触发对话事件等需要手动执行的操作,  才可以继续下一个事件
                self.eventIndex += 1
                 
                match(e["type"]):
                    case "speakTip":
                        if self.msgID is None:
                            self.msgID = ShowDiaLog.showDialog(close=False,title=e["data"][0],imageName=e["data"][1],text=e["msg"])
                        else:
                            ShowDiaLog.updateDialog(self.msgID,title=e["data"][0],imageName=e["data"][1],text=e["msg"])
                        self.eventStop = True # 事件暂停
                        # 如果对话事件是最后一个事件.那么事件对话框会在线程暂停结束之后消失
                        if self.eventIndex == len(self.eventArr):
                            self.eventTipClear = False
                        # 每次循环稍微等待一会,保证事件执行顺序不出错
                        sleep(0.1)
                    case "setBlock":  # 转换图块
                        # 如果楼层为空, 那么默认就是当前楼层
                        flooName = self.mg.floorName
                        if e["floorId"] != "":
                            flooName = e["floorId"]
                        for SKey in GC.GC_SourceMgr:
                            kName = GC.GC_SourceMgr[SKey].get("name")
                            if not kName is None and kName == e["blockName"]:
                                self.mg.updataFPoint(int(e["loc"][0]),int(e["loc"][1]),SKey,flooName)
                                self.mg.updataFPoint(x,y,0,flooName)
                                # self.mg.changeFloor
                                break

                    case "openDoor":  # 开门 通过事件开门, 并非寻常的触发了钥匙开门事件
                        pass
                        
                    case "closeDoor":  # 关门
                        pass

                    case "playSound":  # 播放音效
                        self.music.PlaySound(e["name"])

                    case "hide":  # 隐藏事件 将该点事件移除
                        if e["remove"]:
                            del event[f"{x},{y}"]

                    case "tip":  # 消息提示
                        ShowDiaLog.showTips(e["text"])

                    case "input":  # 接受输入
                        pass

                    case "useItem":  # 使用道具
                        self.bag.rmPackItemName(e["id"])

                    case "addItem":  # 获得道具 ,id 为道具的名称
                        self.bag.addItemByName(e["id"],e["value"])

                    case "exit":  # 立刻结束当前事件
                        break
                        
                    case "changeFloor":  # 楼层切换
                        if not self.mg.changeFloor(e["floorId"],e["loc"]):
                            ShowDiaLog.showTips(f"切换楼层失败,无效楼层:{e['floorId']}")
                        else:
                            # 播放切换楼层音效
                            self.music.PlaySound("floor1.mp3")
                
        # 保证对话事件的连续性每次事件共用一个对话id
        if not self.msgID is None and self.eventTipClear:
                # 将存放对话id的首位弹出,
                ShowDiaLog.rmDialog(self.msgID)
                self.msgID = None
        
        self.__Active = False


    def _execEvent(self):
        """继续往下执行事件"""
        # 判断事件是否暂停执行, (对话事件需要手动继续)
        if self.eventStop:
            # 如果是触发了对话就结束了事件,那么 eventTipClear == False,需要再次手动触发一次,保证事件能够正常按照预期流程运行
            if not self.eventTipClear:
                self.eventTipClear = True
                # 将存放对话id的首位弹出,
                ShowDiaLog.rmDialog(self.msgID)
                self.msgID = None
            # 关闭事件暂停必须等所有的逻辑都执行结束之后,不然容易造成数据的紊乱
            self.eventStop = False